import React, { useEffect, useRef, useState } from "react"
import {
  GridView,
  Image,
  NestedScrollBody,
  NestedScrollHeader,
  ScrollView,
  StickyHeader,
  StickySection,
  Text,
  View
} from "@tarojs/components"
import GpContainer from "@/components/GpContainer"
import { useSetState, useNavigationOpacity, NAVIGATION_BASE_LAYOUT } from "@/utils/hooks"
import styles from "./index.module.scss"
import clsx from "clsx"
import GpShareButton from "@/components/GpShareButton"
import Taro, { getCurrentInstance, useRouter } from "@tarojs/taro"
import { getContentSpecialDetail } from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import GpNavbar from "@/components/GpNavbar"
import GpNoteItem from "../../note/components/GpNoteItem"
import { ScrollViewProps } from "@tarojs/components/types/ScrollView"
import { isSkyline } from "@/utils/core"

type IParams = {
  /** 内容专题id */
  id: string
}
type IState = {
  /** 选择的一级类目值 */
  firstValue?: number
  /** 显示的笔记列表 */
  notes: IApiRelative.IGetContentSpecialDetail.ContentSpecialDetailNote[]
  /** 内容专题详情数据 */
  detail: Omit<IApiRelative.IGetContentSpecialDetail.IResData, "notes">
  /** 渲染后端是否为skyline */
  skyline: boolean
}
/**
 * @page 内容专题
 */
export default function ContentSpecial() {
  const router = useRouter<IParams>()
  const [layout, setLayout] = useState<NavigationBaseLayout>(NAVIGATION_BASE_LAYOUT)
  const [state, setState] = useSetState<IState>({
    notes: [],
    detail: {
      categorys: []
    } as any,
    skyline: isSkyline()
  })
  const [opacity, scrollHandler] = useNavigationOpacity(state.skyline)
  const detailRef = useRef<Pick<IApiRelative.IGetContentSpecialDetail.IResData, "notes">>({
    notes: []
  })
  useEffect(() => {
    fetchDetail()
  }, [])

  async function fetchDetail() {
    try {
      Taro.showLoading()
      const res = await getContentSpecialDetail({ id: router.params.id })
      Taro.hideLoading()
      if (requestIsFullfilled(res)) {
        const { notes, ...rest } = res.data.data
        detailRef.current.notes = notes
        setState({
          detail: rest
        })
        if (rest.categorys.length > 0) {
          const firstLevel = rest.categorys[0]
          handleFirstValueChange(firstLevel.value)
        }
      }
    } catch (error) {
      Taro.hideLoading()
    }
  }
  function handleFirstValueChange(activeKey: number) {
    setState({
      firstValue: activeKey,
      notes: detailRef.current.notes.filter(l => l.categoryId === activeKey)
    })
  }
  function handleNoteLikeSuccess(
    noteItem: PrimaryKey<number>,
    meta: IApiRelative.INoteLikeSwitch.IResData
  ) {
    const _notes = state.notes.concat()
    const finder = _notes.find(l => l.id === noteItem.id)
    if (finder) {
      finder.isSelfLike = meta.isLike
      finder.likeCount = meta.likeCount
      setState({ notes: _notes })
    }
    // 同步总数据里的当前笔记
    const f = detailRef.current.notes.find(l => l.id === noteItem.id)
    if (f) {
      f.isSelfLike = meta.isLike
      f.likeCount = meta.likeCount
    }
  }
  function handleScroll({ detail }: { detail: ScrollViewProps.onScrollDetail }) {
    scrollHandler(detail.scrollTop)
  }
  function renderNavigation() {
    return (
      <GpNavbar
        className="absolute"
        navigationBarPlaceholder={false}
        navigationBarBackgroundColor={`rgba(255,255,255,${opacity})`}
        arrowLeftProps={{
          color:
            opacity >= 0.5 ? `rgba(51, 51, 51, ${opacity})` : `rgba(255, 255, 255, ${1 - opacity})`
        }}
        onLayout={setLayout}
      />
    )
  }
  function renderBaseInfo() {
    const { detail } = state
    return (
      <NestedScrollHeader>
        <View
          style={{
            backgroundImage: `url(${detail.thumbnail})`,
            backgroundPosition: "left top",
            backgroundSize: "100% auto"
          }}
          className="box-border h-500px bg-no-repeat px-32px relative"
        >
          <View
            style={{
              position: "absolute",
              background: "rgba(0, 0, 0, 0.4)",
              left: 0,
              top: 0,
              right: 0,
              bottom: 0,
              zIndex: 0
            }}
          ></View>
          <View
            style={{
              height: layout.statusBarHeight + layout.navigationHeight + "px"
            }}
          ></View>
          <Text className="text-white text-40px font-500 mt-48px relative">#{detail.title}</Text>
          <View className="text-white text-28px mt-24px ellipse_2 leading-32px relative">
            {detail.description}
          </View>
          <View className="flex flex-row items-center justify-between mt-34px relative">
            <View className="flex flex-row items-center box-border text-white text-28px">
              <Image
                src="/images/yikao-community/content-special-loc.png"
                className="w-36px h-36px"
              />
              {detail.areaName}-{detail.projectName}
            </View>
            <View
              style={{
                backgroundColor: "rgba(255, 255, 255, 0.8)"
              }}
              className="box-border h-64px w-160px flex flex-row justify-center items-center rounded-32px t"
            >
              <GpShareButton
                className={styles.shareBtn}
                iconClassName="inline-block mr-10px pl-0"
                shareText="分享"
                icon="icon-fenxiang"
                iconSize={40}
              />
            </View>
          </View>
          {/* skyline层级问题, 导致filter面板圆角部分出不来，故模拟filter面板顶部部分 */}
          {state.skyline && (
            <View
              style={{
                position: "absolute",
                background: "#ffffff",
                left: 0,
                bottom: -2,
                right: 0,
                zIndex: 0,
                height: "16px",
                borderRadius: "16px 16px 0 0"
              }}
            ></View>
          )}
        </View>
      </NestedScrollHeader>
    )
  }
  function renderFilters() {
    return (
      <NestedScrollHeader>
        <StickySection>
          <StickyHeader>
            {/* skyline模式下不支持margin-left为负数, 所以用top替代 */}
            <View
              className={clsx(
                styles.contentPannel,
                state.skyline ? styles.skylineContentPannel : styles.webviewContentPannel
              )}
            >
              <ScrollView scrollX className={styles.filters}>
                {state.detail.categorys.map(l => (
                  <View
                    className={clsx(styles.filter, {
                      [styles.filterActive]: state.firstValue === l.value
                    })}
                    key={l.value}
                    onClick={() => handleFirstValueChange(l.value)}
                  >
                    {l.label}
                  </View>
                ))}
              </ScrollView>
            </View>
          </StickyHeader>
        </StickySection>
      </NestedScrollHeader>
    )
  }
  function renderContentNotes() {
    return (
      <NestedScrollBody>
        <View
          style={{
            width: "100%",
            height: "100%"
          }}
        >
          <ScrollView
            scrollY
            type="custom"
            associativeContainer="nested-scroll-view"
            showScrollbar={false}
            className={clsx(styles.list, {
              [styles.webviewList]: !state.skyline
            })}
          >
            <GridView type="masonry" crossAxisCount={2} crossAxisGap={5} mainAxisGap={5}>
              {state.notes.map(l => (
                <GpNoteItem
                  skyline={state.skyline}
                  key={l.id}
                  noteItem={{
                    id: l.id,
                    image: l.thumbnail,
                    actionFlag: false,
                    avatar: l.createdByHead,
                    fileType: l.fileType,
                    liked: l.isSelfLike,
                    likes: l.likeCount,
                    name: l.createdByName,
                    title: l.title,
                    videoFlag: true,
                    content: l.description
                  }}
                  onLike={handleNoteLikeSuccess}
                />
              ))}
            </GridView>
          </ScrollView>
        </View>
      </NestedScrollBody>
    )
  }
  return (
    <GpContainer
      className="h-full min-h-screen"
      style={{
        backgroundColor: "#F7F7F7"
      }}
      shareConfig={{
        title: state.detail.title
      }}
    >
      {renderNavigation()}
      <ScrollView
        type="nested"
        scrollY
        showScrollbar={false}
        style={{
          width: "100%",
          height: "100%"
        }}
        onScroll={handleScroll}
      >
        {renderBaseInfo()}
        {renderFilters()}
        {renderContentNotes()}
      </ScrollView>
    </GpContainer>
  )
}
